package com.enjoyor.health.HGPT.web.rest;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.enjoyor.health.HGPT.core.config.Constant;
import com.enjoyor.health.HGPT.core.config.WxAppConfig;
import com.enjoyor.health.HGPT.core.dto.FullUserInfoAppDto;
import com.enjoyor.health.HGPT.core.dto.UserInfoAppDto;
import com.enjoyor.health.HGPT.core.dto.UserWatchConfigDto;
import com.enjoyor.health.HGPT.core.entity.UserInfo;
import com.enjoyor.health.HGPT.core.entity.UserInfoApp;
import com.enjoyor.health.HGPT.service.BizNewsService;
import com.enjoyor.health.HGPT.service.BizUserService;
import com.enjoyor.health.HGPT.service.BizWatchService;
import com.enjoyor.health.HGPT.util.SmsUtil;
import com.enjoyor.health.HGPT.web.CodeEnum;
import com.enjoyor.health.HGPT.web.RetResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * APP的用户管理接口
 * @author Zhu Min
 * @date 2023/12/20 11:43
 */
@Slf4j
@Api(value = "APP用户接口", tags = {"APP接口"})
@CrossOrigin
@RequestMapping("/app/user")
@RestController
public class AppUserController {

    @Autowired
    private WxAppConfig wxAppConfig;
    @Autowired
    private BizUserService bizUserService;
    @Autowired
    private BizNewsService bizNewsService;
    @Autowired
    private BizWatchService bizWatchService;
    @Autowired
    private SmsUtil smsUtil;

    @ApiOperation(value = "发送短信登录验证码")
    @PostMapping("/sendSmsCode")
    public RetResult sendSmsCode(String phone){
        if (StringUtils.isBlank(phone)){
            return new RetResult(CodeEnum.PARAM_MISS);
        }
        JSONObject codeJSON = Constant.SMS_CODE_CACHE.getIfPresent(phone);
        if (codeJSON == null){
            //发短信
            Random random = new Random();
            String randomNumber = String.valueOf(random.nextInt(9000) + 1000);
            codeJSON = new JSONObject();
            codeJSON.put("code", randomNumber);
            codeJSON.put("time", LocalDateTime.now().toString());
            Constant.SMS_CODE_CACHE.put(phone, codeJSON);
            log.info("{} - {}", phone, randomNumber);
            //发送
            JSONObject ret = smsUtil.senMassage(phone, randomNumber);
            log.info("发送短信返回：{}", ret.toJSONString());
            return new RetResult().setResult(codeJSON);
        }else {
            //不发短信，还没超过1分钟
            log.info("{} - {}", phone, codeJSON.toJSONString());
            return new RetResult(CodeEnum.TRY_LATER).setResult(codeJSON);
        }
    }

    @ApiOperation(value = "APP登录接口")
    @PostMapping("/login")
    public RetResult login(String phone, String smsCode, String password, String type){
        boolean isLoginSuccess = false;
        if ("1".equals(type)){
            JSONObject codeJSON = Constant.SMS_CODE_CACHE.getIfPresent(phone);
            if (codeJSON !=null && StringUtils.isNotBlank(smsCode) && smsCode.equals(codeJSON.get("code"))){
                isLoginSuccess = true;
            }
        }if ("2".equals(type)){
            //密码登录校验
        }

        if (isLoginSuccess){
            FullUserInfoAppDto dto = new FullUserInfoAppDto();
            //判断是否新用户
            UserInfoApp userInfoApp = bizUserService.getUserInfoAppByPhone(phone);
            UserInfo userInfo = bizUserService.getByPhone(phone);
            if (userInfoApp == null){
                //创建APP新用户
                dto = bizUserService.regAppNewUser(phone);
            }else {
                dto.setUserInfo(userInfo);
                dto.setUserInfoApp(userInfoApp);
            }
            //返回用户信息和TOKEN
            String userId = dto.getUserInfo().getId();
            dto.setUserId(userId);
            StpUtil.login(userId);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            dto.setToken(tokenInfo);
            return new RetResult().setResult(dto);
        }else {
            return new RetResult(CodeEnum.LOGIN_FAILED);
        }
    }

    @ApiOperation(value = "APP登出接口")
    @PostMapping("/logout")
    public RetResult logout(String userId){
        StpUtil.logout();
        return new RetResult();
    }

    @ApiOperation(value = "获取用户信息")
    @PostMapping("/getUserInfo")
    public RetResult getUserInfo(String userId){
        UserInfo userInfo = bizUserService.getByUserId(userId);
        UserInfoAppDto dto = new UserInfoAppDto();
        BeanUtil.copyProperties(userInfo, dto);
        dto.setUserId(userId);
        String birthday = StringUtils.isNotBlank(dto.getIdNumber()) && dto.getIdNumber().length() >14? dto.getIdNumber().substring(6,14):"";
        if (birthday.length()==8){
            birthday = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyyMMdd"))
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        dto.setBirthday(birthday);
        if (userInfo.getGender()!=null){
            dto.setGenderString(userInfo.getGender()==1?"女":"男");
        }
        return new RetResult().setResult(dto);
    }

    @ApiOperation(value = "更新用户信息")
    @PostMapping("/updateUserInfo")
    public RetResult modifyUserInfo(@RequestBody UserInfoAppDto userInfoAppDto){
        if (userInfoAppDto == null || StringUtils.isBlank(userInfoAppDto.getUserId())){
            return new RetResult(CodeEnum.NO_USER_INFO);
        }


        UserInfo userInfo = bizUserService.getByUserId(userInfoAppDto.getUserId());
        if (StringUtils.isNotBlank(userInfoAppDto.getBirthday()) && userInfoAppDto.getBirthday().length()==10){
            if (StringUtils.isNotBlank(userInfo.getIdNumber()) && userInfo.getIdNumber().length()>14){
                userInfoAppDto.setIdNumber(userInfo.getIdNumber().substring(0, 6) + userInfoAppDto.getBirthday().replaceAll("-", "") + userInfo.getIdNumber().substring(14));
            }else {
                userInfoAppDto.setIdNumber("000000" + userInfoAppDto.getBirthday().replaceAll("-", "") + "0000");
            }
        }
        if (StringUtils.isNotBlank(userInfoAppDto.getUserId())){
            userInfoAppDto.setId(userInfoAppDto.getUserId());
        }
        if (StringUtils.isNotBlank(userInfoAppDto.getGenderString())){
            userInfoAppDto.setGender("女".equalsIgnoreCase(userInfoAppDto.getGenderString())?1:0);
        }
        UserInfoAppDto dto = bizUserService.updateAppUserInfo(userInfoAppDto);
        return new RetResult().setResult(dto);
    }

    @ApiOperation(value = "保存用户配置")
    @PostMapping("/saveUserConfig")
    public RetResult saveUserConfig(@RequestBody UserWatchConfigDto dto){
        UserInfoApp userInfoApp = bizUserService.getUserInfoAppByUserId(dto.getUserId());
        if (userInfoApp == null){
            return new RetResult(CodeEnum.NO_USER_INFO);
        }
        return new RetResult().setResult(bizUserService.updateAppWatchConfig(dto));
    }

    @ApiOperation(value = "获取用户配置")
    @PostMapping("/getUserConfig")
    public RetResult getUserConfig(String userId){
        UserInfoApp userInfoApp = bizUserService.getUserInfoAppByUserId(userId);
        if (userInfoApp == null){
            return new RetResult(CodeEnum.NO_USER_INFO);
        }
        UserWatchConfigDto dto = new UserWatchConfigDto();
        dto.setUserId(userId);
        if (StringUtils.isNotBlank(userInfoApp.getConfig())){
            dto = JSONObject.parseObject(userInfoApp.getConfig(), UserWatchConfigDto.class);
        }
        return new RetResult().setResult(dto);

    }

    @ApiOperation(value = "问题反馈接口")
    @PostMapping("/feedback")
    public RetResult feedback(String userId, String title, String content){
        bizNewsService.insertDbFeedbackByApp(userId, title, content);
        return new RetResult();
    }

    @ApiOperation(value = "常见问题接口")
    @PostMapping("/faq")
    public RetResult getFaq(){
        return new RetResult().setResult(bizWatchService.getCommonInfoByType("FAQ"));
    }

    @ApiOperation(value = "删除用户账号接口")
    @PostMapping("/delAccount")
    public RetResult delAccount(){
        bizUserService.deleteAccount(StpUtil.getLoginIdAsString());
        return new RetResult();
    }

}
